﻿using Common.Library;
using Microsoft.Phone.Shell;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace WebSliceBackAgent
{
   
    public class CreateTileImage
    {
     
        public int loopcount =0;
      
        public CreateTileImage(string ShowID, ScheduledAgent agent=null)
        {
          
            loopcount++;
            if (!Storage.DirectoryExists("/Shared/ShellContent/TileImages"))
            {
                Storage.CreateDirectory("/Shared/ShellContent/TileImages");
            }
            Grid grid = new Grid();
            BitmapImage ProductBitmap = new BitmapImage();
            ProductBitmap.CreateOptions = BitmapCreateOptions.None;
            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream local = myIsolatedStorage.OpenFile("/Images/" + ShowID + ".jpg", FileMode.Open, FileAccess.Read))
                {
                    ProductBitmap.SetSource(local);
                }
            }
            Image ProductImage = new Image();
            ProductImage.Width = 173;
            ProductImage.Height = 173;
            ProductImage.Stretch = Stretch.Fill;
            ProductImage.Source = ProductBitmap;
            grid.Children.Add(ProductImage);
            WriteableBitmap wbmp = new WriteableBitmap(grid, null);
            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (var local = myIsolatedStorage.OpenFile("/Shared/ShellContent/TileImages/" + ShowID + ".jpg", System.IO.FileMode.OpenOrCreate))
                {
                    wbmp.SaveJpeg(local, 173, 173, 0, 100);
                    local.Close();
                    local.Dispose();
                    myIsolatedStorage.Dispose();
                }
            }
            ShellTile tiledata = ShellTile.ActiveTiles.FirstOrDefault();
            if (tiledata != null)
            {
                StandardTileData initialData = new StandardTileData();
                initialData = new StandardTileData
                {
                    BackBackgroundImage = new Uri("isostore:/Shared/ShellContent/TileImages/" + ShowID + ".jpg", UriKind.RelativeOrAbsolute),
                };
                tiledata.Update(initialData);
            }
            if(agent!=null)
                agent.complete();
            
        }
    }
}
